package com.example.onion.hxchat.fragment;

import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.lifecycle.Observer;
import androidx.lifecycle.ViewModelProvider;
import androidx.recyclerview.widget.DividerItemDecoration;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;


import com.example.onion.hxchat.activity.MainActivityWC;
import com.example.onion.hxchat.activity.MsgTestActivity;
import com.example.onion.hxchat.adapter.MyInfoAdapter;
import com.example.databean.InfoBean;
import com.example.onion.hxchat.mvvm.InfoViewModel;
import com.example.onion.hxchat.mvvm.UserViewModel;
import com.example.onion.hxchat.room.entity.Info;
import com.example.onion.hxchat.room.entity.User;
import com.example.onion.hxchat.util.MyLocalDatabaseHelper;
import com.example.onion.hxchat.util.PassWordHelp;
import com.example.superyi.myteam.R;

import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

/**
 * 显示消息对话框的fragment
 * 含version
 */
public class InfoFragment extends Fragment {

    private View view;  //定义view用来设置fragment的layout
    public RecyclerView mRecyclerView;  //定义RecyclerView
    //定义以InfoBean实体类为对象的数据集合
    private List<InfoBean> mList = new ArrayList<>();
    //自定义recyclerveiw的适配器
    private MyInfoAdapter myInfoAdapter;

//    private InfoViewModel infoViewModel;
    private int version = 4;

    private  String accountId;
    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        view = inflater.inflate(R.layout.fragment_info, container, false);
        initRecyclerView();
        initData();
        accountId = PassWordHelp.readPassword(requireContext())[0];
        return view;
    }

    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        InfoViewModel infoViewModel = new ViewModelProvider(requireActivity()).get(InfoViewModel.class);
        infoViewModel.getUsersInfos(accountId).observe(requireActivity(), new Observer<List<Info>>() {
            @Override
            public void onChanged(List<Info> infos) {
                Log.e("INfoFragment","infos bianle");
                for (int i =0;i<infos.size();i++)
                {
                    Log.e("INfoFragment","infos "+i+infos.get(i));
                }
                myInfoAdapter.setmList(infos);
                myInfoAdapter.notifyDataSetChanged();
            }
        });
        UserViewModel userViewModel = new ViewModelProvider(this).get(UserViewModel.class);
        userViewModel.getAllUsers().observe(requireActivity(), new Observer<List<User>>() {
            @Override
            public void onChanged(List<User> users) {
                Log.e("INfoFragment","userbianle");
            }
        });
    }

    @Override
    public void onCreateOptionsMenu(@NonNull Menu menu, @NonNull MenuInflater inflater) {
        super.onCreateOptionsMenu(menu, inflater);
    }

    private MyLocalDatabaseHelper dbHelper;

    private final String TAG = "InfoFragment";

    private void initData() {

//        mList.clear();
//        dbHelper = new MyLocalDatabaseHelper(getContext(), "local.db", null, version);
//        SQLiteDatabase db = dbHelper.getWritableDatabase();
//        String accountId = PassWordHelp.readPassword(getContext())[0];
//        Cursor cursor = db.rawQuery("select * from infoItem where ownerUserId = ?", new String[]{accountId});
//        if (cursor.moveToFirst()) {
//            do {
//                String userName = cursor.getString(cursor.getColumnIndex("userName"));
//                String lastInfo = cursor.getString(cursor.getColumnIndex("lastInfo"));
//                String userId = cursor.getString(cursor.getColumnIndex("userId"));
//                InfoBean infoBean = new InfoBean(userName, lastInfo, userId);
//                Log.e(TAG, "执行到了initdata");
//                mList.add(infoBean);
//            } while (cursor.moveToNext());
//        }
        //一下用于测试不同用户对id为1234发送消息的对话框
        InfoBean infoBean = new InfoBean();
            infoBean.setUserName("请登录其他用户id点击1234发送信息");
            infoBean.setLastInfo("测试的对象的用户id为：1234");
            infoBean.setUserId("1234");
            mList.add(infoBean);
    }

    /**
     * TODO 对recycleview进行配置
     */

    private void initRecyclerView() {


        //获取RecyclerView
        mRecyclerView = view.findViewById(R.id.info_fragment_recyclerview_wc);
        //创建adapter
        myInfoAdapter = new MyInfoAdapter();
        myInfoAdapter.setOnItemClickListener(new MyInfoAdapter.OnItemClickListener() {
            @Override
            public void onClick(int position) {

                Toast.makeText(getContext(), "您点击了" + position + "行", Toast.LENGTH_SHORT).show();
            }

            @Override
            public void onLongClick(int position) {
                Toast.makeText(getContext(), "您长按点击了" + position + "行", Toast.LENGTH_SHORT).show();
            }
        });
        //适配器只负责得到数据，跳转页面由从适配器获取到数据的Activity或者Fragment（本fragment页面）去选择跳转到哪个页面
        myInfoAdapter.setDataGetterListener(new MyInfoAdapter.DataGetterListener() {
            @Override
            public void getItemData(Info infoBean) {//infoBean是通过回到机制从适配器中得到的数据
                Toast.makeText(getContext(), "名字是：" + infoBean.getUserName(), Toast.LENGTH_SHORT).show();
                Intent intent = new Intent(getContext(), MsgTestActivity.class);
                intent.putExtra("chatUserName", infoBean.getUserName());//传递用户昵称至聊天页面(加前缀chat)
                intent.putExtra("chatUserId", infoBean.getUserId());//传递用户id至聊天页面(加前缀chat)
                startActivity(intent);
            }
        });
        //给RecyclerView设置adapter
        mRecyclerView.setAdapter(myInfoAdapter);
        //设置layoutManager,可以设置显示效果，是线性布局、grid布局，还是瀑布流布局
        //参数是：上下文、列表方向（横向还是纵向）、是否倒叙
        mRecyclerView.setLayoutManager(new LinearLayoutManager(getActivity(), LinearLayoutManager.VERTICAL, false));
        //设置item的分割线
        mRecyclerView.addItemDecoration(new DividerItemDecoration(getActivity(), DividerItemDecoration.VERTICAL));
        //RecyclerView中没有item的监听事件，需要自己在适配器中写一个监听事件的接口。参数根据自定义
//        myFriendAdapter.setOnItemClickListener(new CollectRecycleAdapter.OnItemClickListener() {
//            @Override
//            public void OnItemClick(View view, GoodsEntity data) {
//                //此处进行监听事件的业务处理
//                Toast.makeText(getActivity(),"我是item",Toast.LENGTH_SHORT).show();
//            }
//        });
    }

}
